package felix.things.router.mqtt.server.store.message;

import felix.things.router.mqtt.server.common.message.IMessageIdService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Optional;

/**
 * @author Felix
 * @date 2019/8/21
 */
@Service
public class MessageIdServiceImpl implements IMessageIdService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MessageIdServiceImpl.class);

    private final static String CACHE_KEY = "mqtt-server:messageid:num";

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public int getNextMessageId() {
        try {
            while (true) {
                int nextMsgId = (int) (Optional.ofNullable(redisTemplate.opsForValue().increment(CACHE_KEY)).orElse(0L) % 65536);
                if (nextMsgId > 0) {
                    return nextMsgId;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }
        return 0;
    }

    @Override
    @Deprecated
    public void releaseMessageId(int messageId) {
    }


    /**
     * 每次重启的时候初始化
     */
    @PostConstruct
    public void init() {
        redisTemplate.delete(CACHE_KEY);
    }
}
